<template>
  <div v-loading="submitLoading">
    <div class="header-btn">
      <div>{{ title }}</div>
      <div>
        <el-button v-show="!fromDetail" type="primary" @click="addOrUpdateConfirm">确认</el-button>
        <el-button plain type="info" @click="goBack">返回</el-button>
      </div>
    </div>
    <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="120px"
             style="position: relative">
      <div class="wrap g-card" style="margin-bottom: 16px">
        <div class="title-header">基础设置</div>
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-show="!fromDetail" v-model="form.taskName" placeholder="请输入" popper-class="minWidth-inp"
                    style="width: 400px">
          </el-input>
          <div v-show="fromDetail">{{ form.taskName }}</div>
        </el-form-item>
        <el-form-item label="触达方式" prop="sendEdition" required>
          <el-radio-group v-model="form.sendEdition" @change="scrmPersonSopUserRels = []" :disabled="taskId">
            <el-radio label="1">自动</el-radio>
            <el-radio label="2">手动</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.sendEdition == '1'" label="添加超级企微" required>
          <select-supermicro ref="checkDigitalEmployee" v-model="scrmPersonSopUserRels"
                             :btn-info.sync="supermicroBtnInfo" :disabled="fromDetail"
                             :is-single-option="isSingleOption"></select-supermicro>
        </el-form-item>
        <el-form-item label="群聊" required v-if="form.sendEdition == '1'">
          <select-group ref="selectGroup" :isSingleOption.sync="isSingleOption" :btn-info.sync="btnInfo" :disabled="fromDetail" v-model="form.selectGroupList" :customerList.sync="scrmPersonSopUserRels"></select-group>
        </el-form-item>
        <el-form-item v-if="form.sendEdition == '2'" label="群聊" prop="selectGroupList">
          <!--  v-show="!fromDetail" -->
          <el-button v-if="!taskId" class="button-new-tag mb10" size="small" @click="addGroupVisible = true">
            <svg-icon icon-class="add"/>
            添加群聊
          </el-button>
          <div v-if="showGroupList.length > 0" class="tag-wrap">
            <!--!fromDetail  -->
            <el-tag v-for="(item, index) in showGroupList" :key="index" :closable="!taskId" @close="handleClose(index)">
              <div>
                <div>{{ item && item.groupName }}</div>
                <div> 群主：{{ item && item.groupLeaderName }}</div>
              </div>
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-show="!fromDetail" v-model="form.remark" :autosize="{ minRows: 3 }" maxlength="64"
                    placeholder="请添加备注" show-word-limit style="width: 400px" type="textarea">
          </el-input>
          <div v-show="fromDetail">{{ form.remark }}</div>
        </el-form-item>
      </div>
      <div class="wrap g-card">
        <div class="title-header">文案及周期设置</div>
        <el-form-item :label="'共' + form.scrmPersonSopRuleDtos.length + '条规则'" prop="scrmPersonSopRuleDtos"
                      required></el-form-item>
        <!-- 展示文案内容 -->
        <div v-for="(item, index) in form.scrmPersonSopRuleDtos" :key="index" class="copy-card">
          <el-form ref="copyForm" label-position="right" label-width="120px" style="position: relative">
            <el-form-item label="内容文案" prop="title">
              <div>{{ item.title }}</div>
            </el-form-item>
            <el-form-item label="发送时间" prop="sendDate">
              <div v-for="i in sendTimeList" :key="i.label">
                <div v-show="item.sendType === i.label">{{ i.value }}</div>
              </div>
              <div v-for="i in item.sendCycle" :key="i + 'week'">
                <span v-for="x in weekList" :key="x.dictValue">
                  <span v-show="x.dictValue === i">{{ x.dictLabel }}</span>
                </span>
              </div>
              <div v-show="item.sendDate">
                <span>{{ item.sendDate }}</span>
              </div>
            </el-form-item>
            <el-form-item label="文本内容">
              <div>{{ item.content }}</div>
            </el-form-item>
            <el-form-item label="发送内容">
              <div v-for="(x, y) in item.mediaContentDetails" :key="y" class="content-item">
                <div>
                  {{ mediaTypeToText[+x.mediaType] }}：{{ x.name }}
                </div>
              </div>
            </el-form-item>
            <el-form-item label="二维码">
              <div class="content-item">{{ codeToText[item.qrType] }}
                {{ item.activityName ? '：' + item.activityName : '' }}
              </div>
            </el-form-item>
          </el-form>
          <div class="option-span copy-edit">
            <span @click="detailPersonSopRule(index)">详情</span>
            <span v-show="fromDetail" v-hasPermi="['admin:sop:addOrUpdateTempTask']"
                  @click="toImplementDetail(index)">执行详情</span>
            <span v-show="!fromDetail" @click="editPersonSopRule(index)">编辑</span>
          </div>
          <div v-show="!fromDetail" class="right-close" @click="deleteCopyWriting(index)">
            <svg-icon icon-class="right-close"/>
          </div>
        </div>
        <div>
          <el-button v-show="!fromDetail" class="button-new-tag" size="small" style="margin-left: 50px"
                     @click="openPersonSopRule">
            <svg-icon icon-class="add"/>
            添加
          </el-button>
        </div>
      </div>
      <div class="wrap g-card" style="margin-bottom: 16px" v-if="form.sendEdition == '1'">
        <div class="title-header">自动发送设置</div>
        <el-form-item label="发送对象间隔" prop="objectInterval">
          <el-slider
            v-model="form.objectInterval"
            :max="120"
            :min="1"
            range
            :disabled="fromDetail"
            style="width: 800px">
          </el-slider>
        </el-form-item>
        <div>
          <span style="margin-left: 120px;margin-right: 30px">{{ form.objectInterval }}</span>
          <span style="cursor: pointer" :style="fromDetail ? 'color:#ccc;' : 'color:#082aff;'"  @click="fromDetail ? '' : form.objectInterval = [3,5]">使用推荐值</span>
        </div>
        <div style="margin-top: 6px">
            <span
              style="margin-left: 120px;color: #ccc">发送对象间隔是指发送上一个群聊最后一条消息完毕到下一个群聊第一条消息开始发送的间隔时间</span>
        </div>
        <el-form-item label="发送消息间隔" prop="messageInterval">
          <el-slider
            v-model="form.messageInterval"
            :max="60"
            :min="1"
            range
            :disabled="fromDetail"
            style="width: 800px">
          </el-slider>
        </el-form-item>
        <div>
          <span style="margin-left: 120px;margin-right: 30px">{{ form.messageInterval }}</span>
          <span style="cursor: pointer" :style="fromDetail ? 'color:#ccc;' : 'color:#082aff;'" @click="fromDetail ? '' : form.messageInterval = [1,5]">使用推荐值</span>
        </div>
        <div style="margin-top: 6px">
            <span
              style="margin-left: 120px;color: #ccc">发送消息间隔是指发送上一个群聊第一条消息完毕到第二条消息开始发送的间隔时间</span>
        </div>
      </div>
    </el-form>
    <!-- 新增文案及周期设置 -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :visible="writingVisible" title="文案及周期设置"
               width="680px" @close="copyWritingCancel">
      <AddCopyWriting v-if="writingVisible" :detailForm="copyForm" :editIndex="editIndex" :operateFlag="operateFlag"
                      :sendTimeList="sendTimeList" :weekList="weekList" @copyWritingCancel="copyWritingCancel"
                      @copyWritingSure="copyWritingSure"></AddCopyWriting>
    </el-dialog>
    <!-- 添加群聊 -->
    <el-dialog :close-on-click-modal="false" :show-close="false" :visible.sync="addGroupVisible" title="添加群聊"
               width="520px">
      <div v-loading="dialogLoading" class="add-group-dialog">
        <el-input v-model="groupName" class="input-style" clearable placeholder="请输入群聊名称" @input="queryGroup">
          <i slot="suffix" class="el-icon-search"></i>
        </el-input>
        <el-checkbox-group v-model="form.selectGroupList" @change="checkboxChange">
          <el-checkbox v-for="item in groupOptions" :key="item.chatId" :label="item.chatId" class="checkbox-style">
            <div>{{ item.groupName }}</div>
            <div>群主：{{ item.groupLeaderName }}</div>
          </el-checkbox>
        </el-checkbox-group>
        <NormalPagination :currentPage="pageNum" :pageSize="pageSize" :total="total" layout="total,prev,pager,next"
                          @handleCurrentChange="handleCurrentChange"></NormalPagination>
      </div>
      <div slot="footer">
        <el-button @click="addGroupVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import addCopyWriting from './components/addCopyWriting.vue'
import {addGroupSop, editGroupSop, findGroupList, queryGroupSop} from '../../../api/operate/groupSop'
import {nameValidate} from '@/utils/validate'
import selectGroup from "@/components/selectGroup.vue";
import selectSupermicro from "@/components/selectSupermicro.vue";

export default {
  name: 'CreateRules',
  components: {
    AddCopyWriting: addCopyWriting,
    selectGroup,
    selectSupermicro,
  },
  computed: {
    showGroupList() {
      // 列表展示群聊
      return this.form.selectGroupList?.map(item => this.allGroupOptions.filter(option => option.chatId === item)?.[0]) || []
    }
  },
  data() {
    return {
      total: 0,
      pageNum: 1,
      pageSize: 10,
      groupOptions: [],
      allGroupOptions: [],
      dialogLoading: false,
      addGroupVisible: false,
      groupName: '',
      title: '创建规则', // 页面标题
      deptIdObj: null,
      taskId: undefined, // 数据id
      submitLoading: false,
      loading: false, // 新增员工弹窗
      customerName: '', // 客户
      customerList: [], // 新增客户数据
      stashCustomerList: [], // 暂存新增的客户数据
      form: {
        // 基础设置
        taskName: '', // 任务名称
        remark: '',
        sendEdition: '1',
        selectGroupList: [],
        scrmPersonSopRuleDtos: [], // 文案及周期设置
        objectInterval: [3, 5],
        messageInterval: [1, 5],
      },
      rules: {
        taskName: [
          {
            required: true,
            validator: nameValidate('任务'),
            trigger: 'change'
          }
        ],
        selectGroupList: [
          {required: true, message: '请选择群聊', trigger: 'change'}
        ],
        // scrmPersonSopRuleDtos: [
        //   {required: true, message: '请选择文案及周期设置', trigger: 'change'}
        // ]
      },
      // 文案及周期设置
      writingVisible: false,
      operateFlag: '',
      copyForm: {
        title: '', // 文案内容
        sendType: '',
        sendDate: '', // 发送时间
        sendCycle: [], // 周期提醒
        mediaContentDetails: [], // 素材
        qrState: '1',
        materialList: [],
        messagePushId: '',
      },
      editIndex: null, // 控制是添加打开弹窗，清空内容
      addDisabled: false, // 文案查看详情
      weekList: [], // 周期提醒
      // 发送时间列表
      sendTimeList: [
        {
          label: '1',
          value: '指定日期'
        },
        {
          label: '2',
          value: '周期提醒'
        }
      ],
      // 路由参数-详情:true,编辑:false
      fromDetail: false,
      mediaTypeToText: {
        11: 'h5链接',
        5: '海报',
        3: '文件',
        4: '文章',
        99: '险种',
        7: '多媒体',
        8: '本地上传',
        9: '',
        10: '问卷',
        100: '本地上传文件'
      },
      codeToText: {
        1: '员工码',
        2: '渠道活码',
        3: '群活码'
      },
      scrmPersonSopUserRels: [],
      supermicroBtnInfo: '添加超级企微',
      isSingleOption: false,
      btnInfo: '添加群聊',
    }
  },
  methods: {
    confirm() {
      this.addGroupVisible = false
      this.$refs.form.validateField('selectGroupList')
      this.pageNum = 1;
    },
    handleClose(index) {
      this.form.selectGroupList.splice(index, 1)
    },
    checkboxChange(value) {
      console.log(value, 'checkbox')
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.queryGroup();
    },
    async queryGroup() {
      const params = {
        groupName: this.groupName,
        pageNum: this.pageNum,
        delFlag: 0,
        pageSize: 10
      }
      this.dialogLoading = true
      try {
        let res = await findGroupList(params)
        this.dialogLoading = false
        if (res.code === 200) {
          this.total = res.total || 0
          this.groupOptions = res.rows || []

          // 保存群聊信息并去重
          const temp = [...this.groupOptions, ...this.allGroupOptions]
          const map = new Map()
          temp.forEach(item => {
            if (!map.has(item.chatId)) {
              map.set(item.chatId, item)
            }
          })
          this.allGroupOptions = [...map.values()]
          console.log(this.allGroupOptions, 'this.allGroupOptions')
        }
      } catch (error) {
        this.dialogLoading = false
      }
    },
    // 初始化查询
    queryTaskdetail() {
      // 路由跳转带来得参数信息
      this.fromDetail = this.$route.query.fromDetail
      this.taskId = this.$route.query.taskId || undefined
      this.$set(this, 'taskId', this.$route.query.taskId || undefined)
      console.log('this.taskId', this.taskId);
      if (this.fromDetail && this.taskId) {
        this.title = '查看详情'
      } else if (!this.fromDetail && this.taskId) {
        this.title = '编辑任务'
      } else {
        this.title = '创建规则'
      }
      if (this.taskId) {
        this.submitLoading = true
        queryGroupSop(this.taskId)
          .then((res) => {
            if (res.code === 200) {
              this.submitLoading = false
              res.data?.scrmGroupSopMaterialResPOList.forEach(item => {
                item.sendType += ''
                item.sendCycle = item.sendCycle.split(',')
              })
              this.form = {
                ...res.data,
                sendEdition: res.data?.sendEdition ? String(res.data?.sendEdition) : '1'
              }
              if (this.form.sendEdition == '1') {
                this.form.messageInterval = res.data?.messageInterval ? JSON.parse(res.data?.messageInterval) : [1, 5]
                this.form.objectInterval = res.data?.objectInterval ? JSON.parse(res.data?.objectInterval) : [3, 5]
                this.$set(this.form, 'selectGroupList', res.data?.scrmGroupSopRelList)
              }else{
                this.$set(this.form, 'selectGroupList', res.data?.scrmGroupSopRelList.map(item => item.chatId))
              }
              this.form.scrmPersonSopRuleDtos = res.data?.scrmGroupSopMaterialResPOList
              this.allGroupOptions = res.data?.scrmGroupSopRelList
              this.scrmPersonSopUserRels = res.data?.sopUser ? JSON.parse(res.data?.sopUser) : []
              console.log(this.form, 'form')
            }
          })
          .finally(() => {
            this.submitLoading = false
            this.queryGroup()
          })
      } else {
        this.queryGroup()
      }
    },
    // 确认
    addOrUpdateConfirm() {
      if(this.form.sendEdition == '1' && this.scrmPersonSopUserRels.length == 0) return this.$message.error('请先添加超级企微')
      if(this.form.selectGroupList.length == 0 && this.form.sendEdition == '1') return this.$message.error('请选择群聊')
      if(this.form.selectGroupList.length == 0 || this.showGroupList.length == 0 && this.form.sendEdition == '2') return this.$message.error('请选择群聊')
      if(this.form.scrmPersonSopRuleDtos.length == 0) return this.$message.error('请添加至少一条文案与周期设置')
      let scrmGroupSopMaterialList = new Array()
      let selectUser = JSON.parse(JSON.stringify(this.form.scrmPersonSopRuleDtos))
      if (this.form.sendEdition == '1') {
        let arr = JSON.parse(JSON.stringify(this.form.scrmPersonSopRuleDtos))
        scrmGroupSopMaterialList = arr.map(item => {
          return {
            ...item,
            sendCycle: item?.sendCycle.toString(),
            mediaContentDetails: item?.mediaContentDetails.map(itm => {
              if (itm.mediaType == '3') {
                itm.materialUrl = window.globalConfig.SHARE_URL + '/linkFile?id=' + itm.id
              } else if (itm.mediaType == '4') {
                itm.materialUrl = window.globalConfig.SHARE_URL + '/linkArticle?id=' + itm.id
              } else if (itm.mediaType == '10') {
                itm.materialUrl = window.globalConfig.SHARE_URL + '/linkForm?id=' + itm.id
              } else if (itm.mediaType == '7') {
                if (itm?.content == '6') {
                  itm.materialUrl = window.globalConfig.SHARE_URL + '/linkVideo?id=' + itm.id
                }
              }
              return itm
            })
          }
        })
        console.log(scrmGroupSopMaterialList, 'scrmGroupSopMaterialList', arr)
        selectUser = selectUser.map(item => {
          return {
            ...item,
            userId: item.weUserId || item.userId
          }
        })
      } else {
        scrmGroupSopMaterialList = this.form.scrmPersonSopRuleDtos.map(item => {
          item.sendCycle = item.sendCycle.toString()
          return item
        })
      }
      let obj = {
        remark: this.form.remark,
        taskName: this.form.taskName,
        weGroupList: this.form.sendEdition == '1' ? this.form.selectGroupList : this.showGroupList,
        sendEdition: this.form.sendEdition,
        scrmGroupSopMaterialList: scrmGroupSopMaterialList, // 文案及周期设置
        objectInterval: this.form.objectInterval ? JSON.stringify(this.form.objectInterval) : '',
        messageInterval: this.form.messageInterval ? JSON.stringify(this.form.messageInterval) : '',
        sopUser: JSON.stringify(this.scrmPersonSopUserRels.map(item => {
          return  {
            id: item.id,
            weUserId: item.weUserId,
            userName: item.userName
          }}))
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.submitLoading = true
          if (this.$route.query.fromDetail === false) {
            this.handleEditGroup(obj)
            return
          }
          addGroupSop(obj).then((res) => {
            if (res.code === 200) {
              this.$message.success('新增成功')
              this.goBack()
            }
          })
            .finally(() => {
              this.submitLoading = false
            })
        } else {
          this.$message.error('你还未录入完成，请核对后提交！')
        }
      })
    },
    handleEditGroup(obj) {
      const params = {
        ...obj,
        taskId: this.taskId
      }
      editGroupSop(params)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success('编辑成功')
            this.goBack()
          }
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    // 返回
    goBack() {
      this.$router.push({name: 'AllSop', query: { activeName: this.$route.query.activeName}})
    },
    // 跳转执行详情
    toImplementDetail(index) {
      this.$router.push({
        path: 'ExecuteDetail',
        query: {
          taskId: this.taskId,
          ruleId: this.form.scrmPersonSopRuleDtos[index].ruleId
        }
      })
    },
    // 关闭弹窗
    copyWritingCancel() {
      this.writingVisible = false
      this.operateFlag = ''
    },
    // 打开新增文案的弹窗
    openPersonSopRule() {
      this.editIndex = null
      this.operateFlag = 'ADD'
      this.copyForm = {
        title: '', // 文案内容
        sendType: '',
        sendDate: '', // 发送时间
        sendCycle: [], // 周期提醒
        mediaContentDetails: [], // 素材
        qrState: '1',
        materialList: []
      }
      this.writingVisible = true
    },
    // 新增文案
    copyWritingSure(data) {
      if (data.editIndex === null) {
        // 新增
        this.form.scrmPersonSopRuleDtos.push(data.copyForm)
      } else {
        // 编辑
        this.form.scrmPersonSopRuleDtos[data.editIndex] = data.copyForm
      }
      this.writingVisible = false
    },
    // 文案详情
    detailPersonSopRule(index) {
      this.copyForm = this.form.scrmPersonSopRuleDtos[index]
      this.operateFlag = 'DETAIL'
      this.editIndex = index
      this.writingVisible = true
    },
    // 编辑文案
    editPersonSopRule(index) {
      this.copyForm = JSON.parse(JSON.stringify(this.form.scrmPersonSopRuleDtos[index]))
      this.operateFlag = 'EDIT'
      this.editIndex = index
      this.writingVisible = true
    },
    // 删除文案内容
    deleteCopyWriting(index) {
      this.form.scrmPersonSopRuleDtos.splice(index, 1)
      this.$forceUpdate()
    }
  },
  mounted() {
    this.queryTaskdetail()
  },
  created() {
    // 周期
    this.getDicts('sys_sop_cycle').then((res) => {
      if (res.code === 200) {
        this.weekList = res.data
      }
    })
  }
}
</script>

<style lang="scss" scoped>
@import "../../../styles/base.scss";

.header-btn {
  @include headerBtn;
}

.wrap {
  @include titleWrap;
}

.input-style {
  width: 50%;
  margin-bottom: 16px;
}

.checkbox-style {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.table-page {
  text-align: right;
}

.tag-wrap {
  display: flex;
  flex-wrap: wrap;

  ::v-deep .el-tag {
    margin-bottom: 10px;
    height: auto;
    display: flex;
    align-items: center;
    width: fit-content;
  }
}

.copy-card {
  width: 740px;
  background-color: #fafafa;
  position: relative;
  margin: 0 0 10px 32px;

  .content-item {
    width: 400px;
    background-color: #e9e9e9;
    padding: 0 10px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
  }

  .copy-edit {
    position: absolute;
    top: 20px;
    right: 20px;
  }

  .right-close {
    position: absolute;
    right: -2px;
    top: -2px;
    cursor: pointer;
  }
}

.add-group-dialog {
  height: 606px;
}

::v-deep{
  .el-textarea .el-input__count{
    bottom: -4px;
    right: -34px;
  }
}
</style>
